package com.lei.springbootpractice.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.lei.springbootpractice.service.UserService;

@Controller
public class RegisterController {

    private final UserService userService;

    public RegisterController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/register")
    public ModelAndView showRegisterForm() {
        return new ModelAndView("register");
    }

    @PostMapping("/register")
    public String register(@RequestParam String userName,
                          @RequestParam String userID,
                          @RequestParam String password,
                          @RequestParam String confirmPassword,
                          @RequestParam String email, @RequestParam String role,
                          Model model) {
        // 注册时只能选择客户角色
        if (!"customer".equals(role)) {
            model.addAttribute("error", "注册时只能选择客户角色");
            return "register";
        }

        // 验证密码是否匹配
        if (!password.equals(confirmPassword)) {
            model.addAttribute("error", "两次输入的密码不一致");
            return "register";
        }

        // 检查用户ID是否已存在
        if (userService.getUserByUserID(userID) != null) {
            model.addAttribute("error", "该账号已被注册");
            return "register";
        }

        try {
            // 添加新用户
            userService.addUser(userID, userName, password, email,role);
            // 注册成功后重定向到成功提示页面
            return "register-success";
        } catch (Exception e) {
            model.addAttribute("error", "注册失败：" + e.getMessage());
            return "register";
        }
    }
}